package com.git.utils;

import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;

import com.git.domain.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.compression.CompressionCodecs;

public class JWTUtils {
	private static String key = "123456";
	
//	根据id，生成token
	public static String getJWT (String id){
		//生成的样例为:{"alg":"HS256"}{"sub":"1"}
		String compact = Jwts.builder()
		.setSubject(id)
		.signWith(SignatureAlgorithm.HS256, key)
		.compact();
		return compact;
	}
//	根据id，生成token
	public static String getJWT (User user){
		//生成的样例为:{"alg":"HS256"}{"sub":"1"}
		 String token = Jwts.builder().setSubject(user.getUsername())
                 .compressWith(CompressionCodecs.DEFLATE)
                 .signWith(SignatureAlgorithm.HS256, key)
                 .setIssuedAt(new Date())
                 .claim("id", user.getId())
                 .claim("name", user.getUsername())
                 .setExpiration(DateUtils.addDays(new Date(), 7))
        		 .compact();
		return token;
	}
	//根据jwt得到
	public static String parseJWT(String token){
		String id =null;
		try {
			id = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return id;
	}
	//根据jwt得到
	public static Claims parseJWTToClaims(String token){
		return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
	}
	public static String parseJWTToid(String token){
		return parseJWTToClaims(token).getId();
	}
}
